const COMMANDER_VERSION = "0.0.4";
const DEFAULT_SEEK_AMOUNT = 10;
if (!String.prototype.replaceAll) {
	String.prototype.replaceAll = function (searchStr, replaceStr) {
		var str = this;
		if (str.indexOf(searchStr) === -1) {
			return str;
		}
		return str.replace(searchStr, replaceStr).replaceAll(searchStr, replaceStr);
	};
}
const UICommander = {
	__get_keycode: function () {
		/* semi-colon */
		if (libWeb.BrowserEnvironment.isChromeFunc()) {
			return 186;
		} else {
			return 59;
		}
	},
	init: function () {
		run_promise(function () {
			var uic_css = document.createElement("link");
			uic_css.href = "./resources/autocomplete.min.css";
			uic_css.rel = "stylesheet";
			uic_css.type = "text/css";
			uic_css.media = "all";
			document.head.appendChild(uic_css);
			loadScripts(["./resources/autocomplete.min.js"], function (callback) {
				const MAIN_DIV = id("commander_overlay");
				const DATA = UICommander.AUTOCOMPLETE_DATA;
				const INP = id("commander_text_input");
				const WA_SETTINGS_CCSS = id("custom_css_area");
				const SEARCH_BAR = id("search_bar");
				const __KEY_CODE = UICommander.__get_keycode();
				document.addEventListener("keydown", function (event) {
					const keyCode = event.keyCode || event.which;
					const shouldAct = isHidden(MAIN_DIV) && !isFocused(SEARCH_BAR) && !isFocused(WA_SETTINGS_CCSS) && id("search_overlay").classList.contains("search_hidden");
					if (keyCode == __KEY_CODE && event.shiftKey && shouldAct) {
						// key is :
						event.preventDefault();
						UICommander.start();
					}
				});
				INP.addEventListener("keypress", function (event) {
					const keyCode1 = event.keyCode || event.which;
					if (keyCode1 == 13) {
						event.preventDefault();
						UICommander.doCommand(INP.value);
					}
				});
				autocomplete({
					input: INP,
					fetch: function (text, update) {
						text = text.toLowerCase();
						const suggestions = DATA.filter(function (n) {
							if (n["applyOn"] && window.location && window.location.pathname && !window.location.pathname.startsWith(n["applyOn"])) {
								return false;
							}
							return n.value.toLowerCase().startsWith(text);
						});
						update(suggestions);
					},
					onSelect: function (item) {
						INP.value = item.value;
					},
				});
			});
		});
	},
	start: function () {
		if (isHidden(id("commander_overlay"))) {
			show(id("commander_overlay"));
			id("commander_text_input").value = ":";
			id("commander_text_input").focus();
		}
	},
	doCommand: function (text) {
		if (text === null || text === undefined || text.value <= 1) {
			show(id("commnader_text_output"));
			id("commnader_text_output").innerText = "Invalid command.";
			setTimeout(function () {
				hide(id("commnader_text_output"));
			}, 500);
			return;
		} else {
			const f = this.getAutocompleteFunction(text);
			if (f !== null) {
				const query = text.substring(3, text.length);
				f.action(query);
				hide(id("commander_overlay"));
			} else if (text.startsWith(":s ")) {
				const search_query = text.substring(3, text.length);
				id("search_bar").value = search_query;
				SearchBar.search(null);
				hide(id("commander_overlay"));
			} else {
				show(id("commnader_text_output"));
				id("commnader_text_output").innerText = "Unknown command.";
				setTimeout(function () {
					hide(id("commnader_text_output"));
				}, 500);
			}
		}
	},
	AUTOCOMPLETE_DATA: [
		/* Core functions */
		{ value: ":s", label: "Search nTube." },
		{ value: ":settings", label: "Open settings in current tab." },
		{ value: ":trending", label: "Open trending." },
		{ value: ":about", label: "Open about." },
		{ value: ":frontpage", label: "Open the experimental frontpage." },
		{ value: ":home", label: "Open the home page." },
		{ value: ":q", label: "Exits this prompt." },
		/* Video page */
		{ value: ":next", label: "Go to next video or playlist entry.", applyOn: "/watch" },
		{ value: ":comments", label: "Go to the comments section. (And load if we haven't done so)", applyOn: "/watch" },
		{ value: ":desc", label: "Go to the description. (And open it if needed)", applyOn: "/watch" },
		{ value: ":adv", label: "Go to the advanced section. (And open it if needed)", applyOn: "/watch" },
		{ value: ":pbs", label: "Go to the playback settings. (And open it if needed)", applyOn: "/watch" },
		{ value: ":rel", label: "Go to the related section.", applyOn: "/watch" },
		{ value: ":ff", label: "Fast-forward the video by 10 seconds.", applyOn: "/watch" },
		{ value: ":rewind", label: "Rewind the video by 10 seconds.", applyOn: "/watch" },
		/* Channel page */
		{ value: ":comm", label: "Go to the community tab. (And load if needed)", applyOn: "/channel" },
		{ value: ":subscribe", label: "Subscribe or unsubscribe from the channel.", applyOn: "/channel" },
	],
	getAutocompleteFunction: function (input) {
		for (var i0 = 0; i0 < UICommander.AUTOCOMPLETE_FUNCTIONS.length; i0++) {
			const obj = UICommander.AUTOCOMPLETE_FUNCTIONS[i0];
			if (obj.value === input) {
				return obj;
			}
		}
		return null;
	},
	scrollToView: function (item) {
		// TODO: Should we have a workaround for Chromium based browsers and their content-visibility bullshit.
		item.scrollIntoView({ behavior: "smooth" });
	},
	AUTOCOMPLETE_FUNCTIONS: [
		{
			value: ":settings",
			action: function (text) {
				document.location.href = "/settings";
			},
		},
		{
			value: ":trending",
			action: function (text) {
				document.location.href = "/trending";
			},
		},
		{
			value: ":frontpage",
			action: function (text) {
				document.location.href = "/frontpage";
			},
		},
		{
			value: ":home",
			action: function (text) {
				document.location.href = "/";
			},
		},
		{
			value: ":about",
			action: function (text) {
				document.location.href = "/about";
			},
		},
		{
			value: ":q",
			action: function (text) {},
		},
		{
			value: ":comments",
			action: function (text) {
				// Do it thrice since content-visibility breaks shit.
				UICommander.scrollToView(id("_comments_initial_button"));
				UICommander.scrollToView(id("_comments_initial_button"));
				UICommander.scrollToView(id("_comments_initial_button"));
				if (!id("_comments_initial_button").disabled) {
					id("_comments_initial_button").click();
				}
			},
		},
		{
			value: ":rel",
			action: function (text) {
				UICommander.scrollToView(id("related_div"));
				UICommander.scrollToView(id("related_div"));
				UICommander.scrollToView(id("related_div"));
			},
		},
		{
			value: ":adv",
			action: function (text) {},
		},
		{
			value: ":desc",
			action: function (text) {},
		},
		{
			value: ":ff",
			action: function (text) {
				var seekAmount = DEFAULT_SEEK_AMOUNT;
				try {
					seekAmount = parseInt(text) || DEFAULT_SEEK_AMOUNT;
				} catch (ex) {}
				if (id("_primary_player")) {
					id("_primary_player").currentTime += seekAmount;
				}
			},
		},
		{
			value: ":rewind",
			action: function (text) {
				var seekAmount = DEFAULT_SEEK_AMOUNT;
				try {
					seekAmount = parseInt(text) || DEFAULT_SEEK_AMOUNT;
				} catch (ex) {}
				if (id("_primary_player")) {
					id("_primary_player").currentTime -= seekAmount;
				}
			},
		},
	],
};
